<?php


namespace App\Admin\Actions\Import;


use App\Models\AdminUser;
use App\Models\Department;
use App\Transverse;
use Carbon\Carbon;
use Encore\Admin\Actions\Action;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class TransverseImport extends Action
{
    protected $selector = '.import-post';

    public function handle(Request $request)
    {
        $creator = Admin::user();
        $collect = Excel::toCollection(collect([]), $request->file('file'))->first();
        $dept_arr = [];
        $code = $this->getCode();
        $collect = collect($collect)->filter(function ($item, $key) {
            return !empty($item[1]) && !empty($item[2]) && !empty($item[4]) && $key;
        })->values()->map(function ($row, $index) use (&$user_arr, &$dept_arr, $code, $creator) {
            $row7 = trim($row[7]);
            $dept = null;
            if ($row8 = trim($row[8])) {
                $dept = Department::query()->where('name', $row8)->first();
                if (!$dept) {
                    $dept_arr[] = $row8;
                }
            }
            $user = AdminUser::query()->where('name', $row7)->first();
            $number = $code + $index;
            return [
                'code' => 'HX' . $number,
                'name' => trim($row[1]),
                'contract_type' => trim($row[2]),
                'buyer' => trim($row[3]),
                'amount' => $this->amount($row[4]),
                'in_amount' => $this->amount($row[5]),
                'domain' => trim($row[6]),
                'user_id' => $user['id'] ?? 0,
                'user_name' => $user['name'] ?? $row7,
                'department_id' => $dept['id'] ?? 0,
                'sign_date' => $this->getSignDate($row[9]),
                'creator_id' => $creator->id,
                'review_status' => 1,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ];
        })->all();
        if ($dept_arr) {
            $msg = implode(',', $dept_arr) . "\n科室不存在无法关联\n";
            $this->response()->status = false;
            return $this->response()->swal()->error($msg);
        }
        if ($collect) {
            Transverse::query()->insert($collect);
        }
        return $this->response()->success('操作成功')->refresh();
    }

    public function form()
    {
        $this->file('file', '请选择文件')
            ->help('<a target="_blank" href="' . url('/template/transverse-template.xls') . '">模板下载</a>');
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default import-post">批量导入</a>
HTML;
    }

    protected function getCode()
    {
        $obj = Transverse::query()
            ->where('created_at', '>=', date('Y-01-01'))
            ->orderByDesc('id')->first();
        if (!$obj) {
            return date('Y') . str_pad(1, 4, 0, STR_PAD_LEFT);
        } else {
            return substr($obj['code'], 2) + 1;
        }
    }

    protected function getSignDate($time)
    {
        try {
            $time = strtr($time, ['年' => '-', '月' => '-', '日' => '']);
            if (is_numeric($time) && strlen($time) == 5) {
                $date = Carbon::parse('1900-01-01')->subDays(2)->addDays($time)->toDateString();
            } else {
                $date = Carbon::parse($time)->toDateString();
            }
        } catch (\Exception $exception) {
            $date = null;
        }
        return $date;
    }

    protected function amount($amount)
    {
        $amount = strtr($amount, ['万' => '']);
        $amount = trim($amount);
        if (is_numeric($amount)) {
            return $amount;
        }
        return 0;
    }
}
